package com.bw.app.dim;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.bean.TableProcess;
import com.bw.func.TableProcessFunction;
import com.bw.utils.MyKafkaUtil;
import com.bw.utils.MyPhoenixSink;
import com.bw.utils.MysqlUtil;
import com.sun.xml.internal.bind.v2.TODO;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.util.Collector;

public class DimApp {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        String  topic="topic_db";
        String groupId="dimapps";
        DataStreamSource<String> ds = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer(topic, groupId));
        //TODO 3. 过滤非json 数据   保留新增及变化及初始化数据
        SingleOutputStreamOperator<JSONObject> filterJSONDS = ds.flatMap(new FlatMapFunction<String, JSONObject>() {

            @Override
            public void flatMap(String s, Collector<JSONObject> collector) throws Exception {
                JSONObject jsonObject = JSON.parseObject(s);
                String s1 = jsonObject.getString("type");
                if (s1.equals("insert")||s1.equals("update")||s1.equals("bootstrap-insert"))
                {
                    collector.collect(jsonObject);
                }
            }
        });

//TODO 4. 使用FlinkCDC  读取mysql 配置信息表    创建配置流
        DataStream<String> dis1 = MysqlUtil.cdcMysql(env, "gmall_config", "table_process");
//        dis1.print();

//        /TODO 5. 将配置流处理为广播流
        MapStateDescriptor<String, TableProcess> mapState = new MapStateDescriptor<>("mapState", String.class, TableProcess.class);


        BroadcastStream<String> broadcast = dis1.broadcast(mapState);

        //TODO 6. 连接主流和广播流
        BroadcastConnectedStream<JSONObject, String> connect = filterJSONDS.connect(broadcast);

//TODO 7. 处理连接流   根据配置信息处理主流数据（将配置信息存入到状态中  主流读状态）
        SingleOutputStreamOperator<JSONObject> process = connect.process(new TableProcessFunction(mapState));
//        process.print();
        process.print();

//        TODO 8. 将数据写出到Phoenix
//        process.print("最终结果---->");
//        process.addSink(new MyPhoenixSink());



        env.execute();

    }
}
